package org.wzq;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;

/**
 * date:9/5/15
 * author:wzq
 * desc: calculate all spent time
 * Date Time UserID Activity TimeSpent
 */
public class MR_timeSpent {
    public static class TS_Mapper extends Mapper<Object, Text, Text, IntWritable> {
        IntWritable timeSpent = new IntWritable();
        private Text userId = new Text();

        @Override
        public void map(Object k1, Text v1, Context context)
                throws IOException, InterruptedException {
            String[] fields = v1.toString().split(" ");
            String userId = fields[2];
            int time = Integer.parseInt(fields[4]);
            timeSpent.set(time);
            this.userId.set(userId);
            context.write(this.userId, timeSpent); // <k1,v1>
        }
    }


    public static class TS_Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        IntWritable timeSpent = new IntWritable();

        @Override
        public void reduce(Text userId, Iterable<IntWritable> timeSpent, Context context)
                throws IOException, InterruptedException {
            int all = 0;
            for (IntWritable val : timeSpent) {
                all += val.get();
            }
            this.timeSpent.set(all);
            context.write(userId, this.timeSpent); // <k2,v2>
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length < 2) {
            System.err.println("Usage: EventCount <in> <out>");
            System.exit(2);
        }

        Job job = Job.getInstance(conf, "time_spent");
        job.setJarByClass(MR_timeSpent.class);
        job.setMapperClass(TS_Mapper.class);
        job.setCombinerClass(TS_Reducer.class);
        job.setReducerClass(TS_Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}
